<template>
  <div>
    <el-dialog title="注册" :visible.sync="dialogVisible" width="600px" center>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- form表单 -->
        <!-- 头像上传 -->
        <el-form-item label="头像" prop="avatar">
          <el-upload
            :data="uploadObj"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="username">
          <el-input v-model="ruleForm.username"> </el-input> </el-form-item
        ><el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"> </el-input> </el-form-item
        ><el-form-item label="手机" prop="phone">
          <el-input v-model="ruleForm.phone"> </el-input> </el-form-item
        ><el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" show-password>
          </el-input>
        </el-form-item>
        <!-- 图形码 -->
        <el-row class="captcha formInput">
          <el-col :span="16"
            ><div class="grid-content bg-purple">
              <el-form-item prop="code" label="图形码">
                <el-input v-model="ruleForm.code"></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple-light">
              <img :src="captcha" @click="captchaCode" alt="" /></div
          ></el-col>
        </el-row>
        <!-- 手机验证码 -->
        <el-row class="captcha formInput">
          <el-col :span="16"
            ><div class="grid-content bg-purple">
              <el-form-item prop="rcode" label="验证码">
                <el-input v-model="ruleForm.rcode"></el-input>
              </el-form-item></div
          ></el-col>
          <el-col :span="7">
            <div class="grid-content bg-purple-light">
              <el-button @click="rcodeText">获取用户验证码</el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 提交/取消按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >立即创建</el-button
          >
          <el-button @click="resetForm('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      uploadObj: {},
      captcha: process.env.VUE_APP_SECRET + '/captcha?type=sendsms',
      uploadUrl: process.env.VUE_APP_SECRET + '/uploads',
      imageUrl: '',
      dialogVisible: false,
      checked: true,
      ruleForm: {
        username: '',
        phone: '',
        email: '',
        avatar: '',
        password: '',
        code: '',
        rcode: ''
      },
      rules: {
        avatar: [
          { required: true, message: '头像不能为空', trigger: 'change' }
        ],
        username: [
          { required: true, message: '昵称不能为空', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('邮箱不能为空'))
              }
              // eslint-disable-next-line
              const reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
              if (!reg.test(value)) {
                return callback(new Error('请输入正确邮箱'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入正确的密码', trigger: 'blur' },
          { min: 6, max: 12, message: '请输入6-12位的数字', trigger: 'blur' }
        ],
        phone: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('手机号码不能为空'))
              }
              const reg = /^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/
              if (!reg.test(value)) {
                return callback(new Error('请输入正确的手机号码'))
              }
              callback()
            },
            trigger: 'blur'
          }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '请输入正确的验证码', trigger: 'blur' }
        ],
        rcode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '请输入正确的验证码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    captchaCode () {
      this.captcha =
        process.env.VUE_APP_SECRET + '/captcha?type=sendsms&f=' + Date.now()
    },
    submitForm (formName) {
      this.$refs[formName].validate(async valid => {
        // 如果错误错误就直接退出
        if (!valid) return
        // 发送axios请求
        const res = await this.$axios.post('/register', this.ruleForm)
        // console.log(res);
        // console.log(res)
        // 判断是否正确
        if (res.code) {
          // 弹窗提示注册成功
          this.$message({
            type: 'success',
            message: '注册成功',
            duration: 1500
          })
          // 清空表格
          this.$refs[formName].resetFields()
          this.imageUrl = ''
          // 关闭注册页面
          this.dialogVisible = false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    async rcodeText () {
      let num = 0
      // validateField 校验表单的方法
      this.$refs.ruleForm.validateField(['phone', 'code'], errorMessage => {
        if (!errorMessage) {
          num++
        }
      })
      // 判断手机号和code写了就执行这一步
      if (num === 2) {
        // console.log(num)
        // await 是可以把异步的代码写成同步的形式
        const res = await this.$axios.post('/sendsms', {
          phone: this.ruleForm.phone,
          code: this.ruleForm.code
        })
        // 判断code值
        // console.log(res)
        if (res.code === 200) {
          this.$message({
            showClose: true,
            message: '验证码是: ' + res.data.captcha,
            type: 'success',
            duration: 10000
          })
        } else {
          this.$message({
            type: 'error',
            message: res.data.message,
            duration: 2000
          })
          // 刷新图形码
          this.captchaCode()
        }
      }
    },
    // 图片上传前
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG|PNG|GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      this.uploadObj.image = file
      return isImage && isLt2M
    },
    // 图片上传后的
    handleAvatarSuccess (res, file) {
      // 判断code是否正确
      // console.log(res);
      if (res.code === 200) {
        // 正确就预览
        this.imageUrl = URL.createObjectURL(file.raw)
        // 把服务器返回的图片地址赋值给avatar
        this.ruleForm.avatar = res.data.file_path
      } else {
        // 返回错误信息
        this.$message({
          type: 'error',
          message: res.message,
          duration: 1000
        })
      }
    }
  },
  created () {
    this.captcha =
      process.env.VUE_APP_SECRET + '/captcha?type=sendsms&f=' + Date.now()
  }
}
</script>
<style>
.captcha img {
  width: 100%;
  height: 40px;
  margin-left: 22px;
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px !important;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
